/*
    This file is part of tPortal.

    tPortal is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    tPortal is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with tPortal.  If not, see <http://www.gnu.org/licenses/>.

    The original code was written by Sebastien Bettinger <sebastien.bettinger@gmail.com>

 */

package net.tinyportal.servlet;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.UnavailableException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.tinyportal.Constant;
import net.tinyportal.bean.PortletHolder;
import net.tinyportal.javax.portlet.TpPortletContext;
import net.tinyportal.javax.portlet.TpPortletURL;
import net.tinyportal.javax.portlet.TpRenderRequest;
import net.tinyportal.javax.portlet.TpRenderResponse;

public class Portlet2Servlet extends HttpServlet  {
	/**
	 * 
	 */
	private static final long serialVersionUID = 7934374005770615573L;
	
	/**
	 * Jsp du portail, définie dans le web.xml
	 */
	private String portalJsp;

	/**
	 * A l'initialisation de la servlet, on va initialiser les différents portlets présent<br/>
	 * <br/>
	 * Pour cela, on va parcourir le répertoire des portlets, les initialiser un a un
	 */
	public void init(ServletConfig config) {
		try {
			super.init(config);
			/*
			 * On va charger les portlets disponibles
			 */
			ServletContext context = getServletContext();

			/*
			 * On charge la valeur de la jsp
			 */
			portalJsp = context.getInitParameter("JSPPortal");
			
			/*
			 * On va charger les portlets présent dans le répertoire indiqué
			 */
			PortletLoader pLoader = new PortletLoader(context);
			String portlets_real_Path = context.getRealPath(Constant.portlets_path);
			File portletsPathFile = new File(portlets_real_Path);
			File[] portletList = portletsPathFile.listFiles();
			for (File portlet_directory : portletList) {
				try {
					Portal.addPortlets(pLoader.load(portlet_directory));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
			}
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			/*
			 * On commence par créer/récupérer la session de l'utilisateur,
			 * dans le cas d'un utilisateur non authentifié, on crée simplement une session anonyme
			 */

			/*
			 * Map des portlets passé a la jsp pour l'affichage du portail
			 */
			Map<String, PortletHolder> portletsMap = new HashMap<String, PortletHolder>();

			/*
			 * Affichage
			 * On va parcourir les portlets présent dans l'objet portal
			 * et s'en occuper
			 */
			for(String portletName: Portal.getPortletSet()) {
				/*
				 * Si le portlet n'est pas actif, on continue
				 */
				if (!Portal.isActivePortlet(portletName)) continue;

				/*
				 * On récupère le bean associé au portlet
				 */
				PortletHolder portletHolder = Portal.getPortlet(request, portletName);
				GenericPortlet portlet = portletHolder.getPortlet();

				/*
				 * DOGET
				 */
				String portletId = TpPortletURL.getPortletId(portletHolder);

				TpPortletContext TpPortletContext = (TpPortletContext) portlet.getPortletContext();
				TpRenderRequest TPrequest = new TpRenderRequest(portletHolder, request, TpPortletContext);
				TpRenderResponse TPresponse = new TpRenderResponse(response, portletId);

				/*
				 * On positionne le bean portlet dans la requête pour pouvoir y accéder depuis les taglibs
				 */
				TPrequest.setAttribute(Constant.session_portlet_bean,portletHolder);

				portletHolder.setRenderRequest(TPrequest);
				portletHolder.setRenderResponse(TPresponse);
				portletHolder.setPortletConfig(portlet.getPortletConfig());

				try {
					/*
					 * On effectue les taches d'ACTION
					 */
					StringBuffer sb = new StringBuffer(portletId).append("_").append("action");
					String action = request.getParameter(sb.toString());
					if ("action".equalsIgnoreCase(action)) {
						Portal.doAction(request, response, portletHolder, portlet);
					} else if ("render".equalsIgnoreCase(action)) {
						Portal.doRender(request, response, portletHolder, portlet);
					} else {
						Portal.setWindowState(request, portletHolder);
						Portal.setPortletMode(request, portletHolder);
					}
					/*
					 * de RENDU
					 */
					Portal.doRender(request, response, portletHolder, portlet);

					/*
					 * 
					 */
					try {
						Portal.doRefresh(request, response, portletHolder, portlet);
					} catch (PortletException e) {
						log(e.getMessage());
						portletHolder.setTitle("Erreur sur le portlet");
						portletHolder.setContent("/!\\ Erreur !!" + e.getMessage());
					}
					/*
					 * Enfin, on place le portletHolder dans la map des portlets
					 * disponible
					 */
					portletsMap.put(portletName, portletHolder);
				} catch (UnavailableException ue) {
					portlet.destroy();
					Portal.addDisabledPortlet(portletName);

				} catch (PortletException e) {
					log(e.getMessage());
					portletHolder.setTitle("Erreur sur le portlet");
					portletHolder.setContent("/!\\ Erreur !!" + e.getMessage());
				}
			}

			/*
			 * On fait le rendu du portail
			 */
			RequestDispatcher servletDispatcher;

			request.setAttribute(Constant.session_portlet_bean_map, portletsMap);
			//			request.setAttribute(Constant.session_portlet_bean_list, portletsBean);
			response.setHeader("Content-Type", "text/html");

			ServletContext context = getServletContext();
			servletDispatcher = context.getRequestDispatcher(portalJsp);
			servletDispatcher.include(request, response);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
